package tech.heptagram.staff.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tech.heptagram.staff.exception.StaffApiException;
import tech.heptagram.staff.mapper.DepartmentStaffMapper;
import tech.heptagram.staff.domain.DepartmentStaff;
import tech.heptagram.staff.service.DepartmentStaffService;
import tech.heptagram.staff.util.AssertUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author daxiong
 * @date 2019/3/25
 */
@Service
@Slf4j
public class DepartmentStaffServiceImpl implements DepartmentStaffService {

    @Resource
    private DepartmentStaffMapper departmentStaffMapper;

    @Override
    public void saveOrUpdate(List<Integer> departmentIds, String staffCode, String modifiedBy) {
        AssertUtils.notNull(staffCode,"code不能为空");
        AssertUtils.notNull(modifiedBy,"修改人不能为空");
        if (departmentIds == null || departmentIds.size() == 0){
            throw new StaffApiException("部门ID不能为空");
        }

        //删除原先旧部门，再添加新部门关系
        DepartmentStaff removePo = new DepartmentStaff();
        removePo.setStaffCode(staffCode);
        removePo.setModifiedBy(modifiedBy);
        departmentStaffMapper.deletedByStaffCode(removePo);

        DepartmentStaff savePo = new DepartmentStaff();
        savePo.setStaffCode(staffCode);
        savePo.setModifiedBy(modifiedBy);
        savePo.setCreatedBy(modifiedBy);
        for (Integer departmentId: departmentIds){
            savePo.setDepartmentId(departmentId);
            departmentStaffMapper.insert(savePo);
        }
    }

}
